<!--
  Copyright 2019 Hackware SpA <human@hackware.cl>
  This file is part of "Hackware Userland" and licensed under the terms
  of the GNU Affero General Public License version 3, or (at your option)
  a later version. You should have received a copy of this license along
  with the software. If not, see <https://www.gnu.org/licenses/>.
-->

<template>
  <div>
    <select
      class="custom-select"
      disabled="readonly"
      :name="!readonly ? name : undefined"
    >
      <option
        v-for="option in options"
        :key="option.const"
        :value="option.const"
        :selected="isDefault(option)"
        v-text="option.title"
      />
    </select>
    <input
      v-if="!!property.default"
      type="hidden"
      :name="name"
      :value="property.default"
    >
  </div>
</template>

<script>
export default {
  name: 'SchemaFormSelectWidget',
  props: {
    name: {
      type: String,
      required: true,
    },
    property: {
      type: Object,
      required: true,
    },
    readonly: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    options() { // Transform enum to oneOf schema spec: [{const: 'x', title: 'y'}, ...]
      let options;
      if ('enum' in this.property) {
        options = this.property.enum.map(val => ({ const: val, title: val }));
      } else if ('oneOf' in this.property) {
        options = this.property.oneOf;
      } else {
        throw ReferenceError('Unsupported select property, must contain "enum" or "oneOf"');
      }
      return options;
    },
  },
  methods: {
    isDefault(option) {
      return this.property.default === String(option.const);
    },
  },
};
</script>
